<script setup lang="ts">
import { ref, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { 
  Shop, 
  Plus, 
  Edit, 
  Delete, 
  Upload, 
  Download,
  Refresh,
  Search
} from '@element-plus/icons-vue'
import { 
  getMerchantInfoService,
  findItemsByMerchantIdService,
  searchItemsByMerchantIdService,
  addItemService,
  updateItemService,
  deleteItemService,
  deleteItemsService,
  enableItemService,
  disableItemService,
  enableItemsService,
  disableItemsService
} from '../../api/merchant'
import { useMerchantStore } from '../../stores/merchant'
import { uploadAvatarService } from '../../api/user'

const router = useRouter()
const merchantStore = useMerchantStore()

// 商品列表数据
const productList = ref([])
const loading = ref(false)
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)

// 选中的商品
const selectedProducts = ref([])

// 搜索关键词
const searchKeyword = ref('')

// 商品对话框
const productDialogVisible = ref(false)
const productDialogTitle = ref('添加商品')
const productForm = ref({
  id: null,
  name: '',
  price: '',
  stock: '',
  image: '',
  category: '',
  isUserAddCategory: 0,
  brand: '',
  spec: ''
})

// 商品状态映射
const statusMap: Record<number, { text: string; type: string }> = {
  0: { text: '待审核', type: 'warning' },
  1: { text: '已上架', type: 'success' },
  2: { text: '已下架', type: 'info' },
  3: { text: '审核未通过', type: 'danger' }
}

// 加载商家信息
const loadMerchantInfo = async () => {
  try {
    const res: any = await getMerchantInfoService()
    if (res.code === 0) {
      merchantStore.setMerchantInfo(res.data)
    }
  } catch (error) {
    console.error('加载商家信息失败:', error)
  }
}

// 加载商品列表
const loadProducts = async () => {
  loading.value = true
  try {
    let res: any
    if (searchKeyword.value.trim()) {
      // 如果有搜索关键词，使用搜索接口
      res = await searchItemsByMerchantIdService(searchKeyword.value, currentPage.value, pageSize.value)
    } else {
      // 否则使用普通列表接口
      res = await findItemsByMerchantIdService(currentPage.value, pageSize.value)
    }
    if (res.code === 0) {
      productList.value = res.data.items || []
      total.value = res.data.total || 0
    }
  } catch (error) {
    console.error('加载商品列表失败:', error)
    ElMessage.error('加载商品列表失败')
  } finally {
    loading.value = false
  }
}

// 搜索商品
const handleSearch = () => {
  currentPage.value = 1
  loadProducts()
}

// 重置搜索
const handleReset = () => {
  searchKeyword.value = ''
  currentPage.value = 1
  loadProducts()
}

// 页码改变
const handlePageChange = (page: number) => {
  currentPage.value = page
  loadProducts()
}

// 打开添加商品对话框
const openAddDialog = () => {
  productDialogTitle.value = '添加商品'
  productForm.value = {
    id: null,
    name: '',
    price: '',
    stock: '',
    image: '',
    category: '',
    isUserAddCategory: 0,
    brand: '',
    spec: ''
  }
  productDialogVisible.value = true
}

// 打开编辑商品对话框
const openEditDialog = (product: any) => {
  productDialogTitle.value = '编辑商品'
  productForm.value = {
    id: product.id,
    name: product.name,
    price: product.price,
    stock: product.stock,
    image: product.image,
    category: product.category,
    isUserAddCategory: product.isUserAddCategory,
    brand: product.brand,
    spec: product.spec
  }
  productDialogVisible.value = true
}

// 上传图片
const handleImageUpload = async (file: any) => {
  try {
    const res: any = await uploadAvatarService(file.raw)
    if (res.code === 0) {
      productForm.value.image = res.data
      ElMessage.success('图片上传成功')
    }
  } catch (error) {
    console.error('图片上传失败:', error)
    ElMessage.error('图片上传失败')
  }
}

// 保存商品
const saveProduct = async () => {
  try {
    if (productForm.value.id) {
      // 编辑商品
      await updateItemService(productForm.value)
      ElMessage.success('商品更新成功')
    } else {
      // 添加商品
      await addItemService(productForm.value)
      ElMessage.success('商品添加成功')
    }
    productDialogVisible.value = false
    loadProducts()
  } catch (error: any) {
    console.error('保存商品失败:', error)
    ElMessage.error(error.response?.data?.message || '保存商品失败')
  }
}

// 删除商品
const deleteProduct = async (id: number) => {
  try {
    await ElMessageBox.confirm('确定要删除该商品吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    await deleteItemService(id)
    ElMessage.success('删除成功')
    loadProducts()
  } catch (error: any) {
    if (error !== 'cancel') {
      console.error('删除商品失败:', error)
      ElMessage.error('删除商品失败')
    }
  }
}

// 批量删除
const batchDelete = async () => {
  if (selectedProducts.value.length === 0) {
    ElMessage.warning('请选择要删除的商品')
    return
  }
  try {
    await ElMessageBox.confirm(`确定要删除选中的 ${selectedProducts.value.length} 个商品吗？`, '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    const ids = selectedProducts.value.map((p: any) => p.id)
    await deleteItemsService(ids)
    ElMessage.success('批量删除成功')
    selectedProducts.value = []
    loadProducts()
  } catch (error: any) {
    if (error !== 'cancel') {
      console.error('批量删除失败:', error)
      ElMessage.error('批量删除失败')
    }
  }
}

// 上架商品
const enableProduct = async (id: number) => {
  try {
    await enableItemService(id)
    ElMessage.success('商品已上架')
    loadProducts()
  } catch (error) {
    console.error('上架失败:', error)
    ElMessage.error('上架失败')
  }
}

// 下架商品
const disableProduct = async (id: number) => {
  try {
    await disableItemService(id)
    ElMessage.success('商品已下架')
    loadProducts()
  } catch (error) {
    console.error('下架失败:', error)
    ElMessage.error('下架失败')
  }
}

// 批量上架
const batchEnable = async () => {
  if (selectedProducts.value.length === 0) {
    ElMessage.warning('请选择要上架的商品')
    return
  }
  try {
    const ids = selectedProducts.value.map((p: any) => p.id)
    await enableItemsService(ids)
    ElMessage.success('批量上架成功')
    selectedProducts.value = []
    loadProducts()
  } catch (error) {
    console.error('批量上架失败:', error)
    ElMessage.error('批量上架失败')
  }
}

// 批量下架
const batchDisable = async () => {
  if (selectedProducts.value.length === 0) {
    ElMessage.warning('请选择要下架的商品')
    return
  }
  try {
    const ids = selectedProducts.value.map((p: any) => p.id)
    await disableItemsService(ids)
    ElMessage.success('批量下架成功')
    selectedProducts.value = []
    loadProducts()
  } catch (error) {
    console.error('批量下架失败:', error)
    ElMessage.error('批量下架失败')
  }
}

// 选择改变
const handleSelectionChange = (selection: any) => {
  selectedProducts.value = selection
}

// 退出登录
const handleLogout = () => {
  merchantStore.clearMerchant()
  ElMessage.success('已退出商家登录')
  router.push('/merchant/auth')
}

onMounted(() => {
  // 检查商家是否已登录
  if (!merchantStore.isLoggedIn || !merchantStore.merchantToken) {
    ElMessage.warning('请先登录商家账号')
    router.push('/merchant/auth')
    return
  }
  
  loadMerchantInfo()
  loadProducts()
})
</script>

<template>
  <div class="merchant-dashboard">
    <!-- 头部 -->
    <div class="dashboard-header">
      <div class="merchant-info">
        <el-avatar :size="60" :src="merchantStore.merchantLogo">
          <el-icon><Shop /></el-icon>
        </el-avatar>
        <div class="info-text">
          <h2>{{ merchantStore.merchantName }}</h2>
          <p>{{ merchantStore.description }}</p>
          <p class="balance">余额：<span class="balance-amount">¥{{ merchantStore.balance?.toFixed(2) || '0.00' }}</span></p>
        </div>
      </div>
      <div class="header-actions">
        <el-button @click="router.push('/merchant/profile')">商家信息</el-button>
        <el-button type="primary" @click="router.push('/merchant/orders')">订单管理</el-button>
        <el-button @click="router.push('/layout')">返回主页</el-button>
        <el-button type="danger" @click="handleLogout">退出登录</el-button>
      </div>
    </div>

    <!-- 工具栏 -->
    <div class="toolbar">
      <div class="toolbar-left">
        <el-button type="primary" :icon="Plus" @click="openAddDialog">添加商品</el-button>
        <el-button :icon="Upload" @click="batchEnable">批量上架</el-button>
        <el-button :icon="Download" @click="batchDisable">批量下架</el-button>
        <el-button type="danger" :icon="Delete" @click="batchDelete">批量删除</el-button>
      </div>
      <div class="toolbar-right">
        <el-input
          v-model="searchKeyword"
          placeholder="搜索商品名称、分类、品牌..."
          clearable
          @keyup.enter="handleSearch"
          @clear="handleReset"
          style="width: 300px; margin-right: 0.5rem"
        >
          <template #append>
            <el-button :icon="Search" @click="handleSearch">搜索</el-button>
          </template>
        </el-input>
        <el-button :icon="Refresh" @click="loadProducts">刷新</el-button>
      </div>
    </div>

    <!-- 商品表格 -->
    <el-table
      :data="productList"
      v-loading="loading"
      @selection-change="handleSelectionChange"
      style="width: 100%"
    >
      <el-table-column type="selection" width="55" />
      <el-table-column label="商品图片" width="100">
        <template #default="{ row }">
          <el-image
            :src="row.image"
            fit="cover"
            style="width: 60px; height: 60px; border-radius: 4px"
          />
        </template>
      </el-table-column>
      <el-table-column prop="name" label="商品名称" min-width="150" />
      <el-table-column prop="price" label="价格" width="100">
        <template #default="{ row }">
          ¥{{ row.price }}
        </template>
      </el-table-column>
      <el-table-column prop="stock" label="库存" width="80" />
      <el-table-column prop="category" label="分类" width="100" />
      <el-table-column prop="brand" label="品牌" width="100" />
      <el-table-column prop="sold" label="销量" width="80" />
      <el-table-column prop="status" label="状态" width="100">
        <template #default="{ row }">
          <el-tag :type="statusMap[row.status]?.type">
            {{ statusMap[row.status]?.text }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="操作" width="200" fixed="right">
        <template #default="{ row }">
          <el-button link type="primary" :icon="Edit" @click="openEditDialog(row)">
            编辑
          </el-button>
          <el-button
            v-if="row.status === 2"
            link
            type="success"
            @click="enableProduct(row.id)"
          >
            上架
          </el-button>
          <el-button
            v-else-if="row.status === 1"
            link
            type="warning"
            @click="disableProduct(row.id)"
          >
            下架
          </el-button>
          <el-button link type="danger" :icon="Delete" @click="deleteProduct(row.id)">
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <div class="pagination">
      <el-pagination
        v-model:current-page="currentPage"
        :page-size="pageSize"
        :total="total"
        layout="total, prev, pager, next, jumper"
        @current-change="handlePageChange"
        :prev-text="'上一页'"
        :next-text="'下一页'"
      />
    </div>

    <!-- 商品对话框 -->
    <el-dialog
      v-model="productDialogVisible"
      :title="productDialogTitle"
      width="600px"
    >
      <el-form :model="productForm" label-width="100px">
        <el-form-item label="商品名称" required>
          <el-input v-model="productForm.name" placeholder="请输入商品名称" />
        </el-form-item>
        <el-form-item label="商品价格" required>
          <el-input v-model="productForm.price" type="number" placeholder="请输入价格" />
        </el-form-item>
        <el-form-item label="库存" required>
          <el-input v-model="productForm.stock" type="number" placeholder="请输入库存" />
        </el-form-item>
        <el-form-item label="商品图片">
          <el-upload
            :auto-upload="false"
            :show-file-list="false"
            :on-change="handleImageUpload"
            accept="image/*"
          >
            <el-button type="primary">上传图片</el-button>
          </el-upload>
          <el-image
            v-if="productForm.image"
            :src="productForm.image"
            style="width: 100px; height: 100px; margin-top: 10px"
          />
        </el-form-item>
        <el-form-item label="分类">
          <el-input v-model="productForm.category" placeholder="请输入分类" />
        </el-form-item>
        <el-form-item label="品牌">
          <el-input v-model="productForm.brand" placeholder="请输入品牌" />
        </el-form-item>
        <el-form-item label="规格">
          <el-input
            v-model="productForm.spec"
            type="textarea"
            :rows="3"
            placeholder="请输入商品规格"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="productDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="saveProduct">保存</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<style scoped lang="scss">
.merchant-dashboard {
  padding: 2rem;
  background: #f5f7fa;
  min-height: 100vh;
}

.dashboard-header {
  background: white;
  padding: 2rem;
  border-radius: 8px;
  margin-bottom: 2rem;
  display: flex;
  justify-content: space-between;
  align-items: center;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);

  .merchant-info {
    display: flex;
    align-items: center;
    gap: 1.5rem;

    .info-text {
      h2 {
        margin: 0 0 0.5rem 0;
        font-size: 1.5rem;
        color: #333;
      }

      p {
        margin: 0;
        color: #666;
        font-size: 0.9rem;
      }

      .balance {
        margin-top: 0.5rem;
        font-size: 1rem;
        color: #333;
        font-weight: 500;

        .balance-amount {
          color: #67c23a;
          font-size: 1.2rem;
          font-weight: 600;
        }
      }
    }
  }
}

.toolbar {
  background: white;
  padding: 1rem 2rem;
  border-radius: 8px;
  margin-bottom: 1rem;
  display: flex;
  justify-content: space-between;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);

  .toolbar-left {
    display: flex;
    gap: 0.5rem;
  }

  .toolbar-right {
    display: flex;
    align-items: center;
    gap: 0.5rem;
  }
}

.el-table {
  background: white;
  border-radius: 8px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
}

.pagination {
  margin-top: 1.5rem;
  display: flex;
  justify-content: center;
}
</style>
